﻿using System.Linq;
using Xoohoo.Infrastructure;
using Xoohoo.Models;
using Xoohoo.Models.InputModels;
using Xoohoo.Repositories;

namespace Xoohoo.Services
{
    public class BulletinService : IBulletinService
    {
        private readonly IBulletinRepository _repository;
        private readonly ICacheModule _cache;
        private readonly string _cacheKey = "Bulletin";

        public BulletinService(IBulletinRepository repository, IModuleRegistry modulesLoaded)
        {
            this._repository = repository;
            this._cache = modulesLoaded.GetModules<ICacheModule>().Last();
        }
    
        public Bulletin GetItem()
        {
            return _cache!=null
                ?_cache.GetItem<Bulletin>(_cacheKey,() => _repository.GetItem(),null) 
                : _repository.GetItem();
            
        }

        public bool Save(BulletinInput bulletin)
        {
            bool result = _repository.Save(bulletin);
            if(result)
                _cache.Invalidate(_cacheKey);
            return result;
        }
    }
}
